package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.District;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.domain.ProjectAuction;
import com.ruoyi.industry.service.IProjectAuctionService;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目-拍卖Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-18
 */
@Service
public class ProjectAuctionServiceImpl implements IProjectAuctionService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectAuctionMapper projectAuctionMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 查询项目-拍卖
     *
     * @param id 项目-拍卖主键
     * @return 项目-拍卖
     */
    @Override
    public ProjectAuction selectProjectAuctionById(Long id)
    {
        return projectAuctionMapper.selectProjectAuctionById(id);
    }

    /**
     * 查询项目-拍卖列表
     *
     * @param projectAuction 项目-拍卖
     * @return 项目-拍卖
     */
    @Override
    public List<ProjectAuction> selectProjectAuctionList(ProjectAuction projectAuction)
    {
//        List<Long> districtIds = new ArrayList<Long>();
//        //查询城市
//        if(projectAuction.getCityId()!=null){
//            districtIds.add(projectAuction.getCityId());
//            projectAuction.setCityIds(districtIds);
//        }else if (projectAuction.getCityId()==null&&projectAuction.getProvinceId()!=null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectAuction.getProvinceId()));
//            districtIds.add(projectAuction.getProvinceId());
//            projectAuction.setCityIds(districtIds);
//        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectAuction.setSupplyUserId(SecurityUtils.getUserId());
//        }
        List<ProjectAuction> projectAuctionList = projectAuctionMapper.selectProjectAuctionListz(projectAuction);
//        for (ProjectAuction auction : projectAuctionList) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(auction.getServicePhone());
//            if (sysUser!=null) {
//                auction.setContactName(sysUser.getNickName());
//                auction.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectAuctionList;
    }

    /**
     * 新增项目-拍卖
     *
     * @param projectAuction 项目-拍卖
     * @return 结果
     */
    @Override
    public int insertProjectAuction(ProjectAuction projectAuction)
    {
        projectAuction.setSupplyUserId(SecurityUtils.getUserId());
        if (projectAuction.getApprovalState()==null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectAuction.setApprovalState(1L);//审核通过
//            } else {
                projectAuction.setApprovalState(0L);//待审核
//            }
        }
        projectAuction.setCreateTime(DateUtils.getNowDate());
        projectAuction.setSerialNumber(IdUtils.fastSimpleUUID());

        SpaceIndustry spaceIndustry = new SpaceIndustry();
        spaceIndustry.setSpaceId(projectAuction.getSerialNumber());
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectAuction.getCreateTime());
        spaceIndustry.setSupplyUserId(projectAuction.getSupplyUserId());
        extracted(projectAuction, spaceIndustry);

        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectAuctionMapper.insertProjectAuction(projectAuction);
    }

    private static void extracted(ProjectAuction projectAuction, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(7);
        spaceIndustry.setReleaseType(0L);
        spaceIndustry.setApprovalState(projectAuction.getApprovalState());
        spaceIndustry.setProvinceId(projectAuction.getProvinceId());
        spaceIndustry.setCityId(projectAuction.getCityId());
        spaceIndustry.setAreaId(projectAuction.getAreaId());
        spaceIndustry.setParkId(String.valueOf(projectAuction.getParkId()));
        spaceIndustry.setLeasePrice(projectAuction.getAuctionPrice());
        spaceIndustry.setSellPrice(projectAuction.getAuctionPrice());
        spaceIndustry.setCoverResource(projectAuction.getCoverResource());
        spaceIndustry.setSpaceAllSize(projectAuction.getAllSize());
        spaceIndustry.setSpaceName(projectAuction.getAuctionName());
        spaceIndustry.setRecomState(projectAuction.getRecomState());
    }

    /**
     * 修改项目-拍卖
     *
     * @param projectAuction 项目-拍卖
     * @return 结果
     */
    @Override
    public int updateProjectAuction(ProjectAuction projectAuction)
    {
        if (projectAuction.getApprovalState() == null) {
            projectAuction.setApprovalState(0L);//待审核
        }
        projectAuction.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectAuction,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectAuction.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectAuction.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByAuctionId(spaceIndustry);
        return projectAuctionMapper.updateProjectAuction(projectAuction);
    }

    /**
     * 批量删除项目-拍卖
     *
     * @param ids 需要删除的项目-拍卖主键
     * @return 结果
     */
    @Override
    public int deleteProjectAuctionByIds(Long[] ids)
    {
        List<ProjectAuction> projectAuctions = projectAuctionMapper.selectProjectAuctionByIds(ids);
        List<String> pathList = new ArrayList<>();
        for (ProjectAuction projectAuction : projectAuctions) {
            spaceIndustryMapper.deleteSpaceRecomById("拍卖",projectAuction.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectAuction.getVrResource(),
                    projectAuction.getImgResource(),
                    projectAuction.getCoverResource(),
                    projectAuction.getVrcover(),
                    projectAuction.getQrCode()
            );
        }
        spaceIndustryMapper.deleteSpaceIndustryByProjectAuctionIds(ids);
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        return projectAuctionMapper.deleteProjectAuctionByIds(ids);
    }

    /**
     * 删除项目-拍卖信息
     *
     * @param id 项目-拍卖主键
     * @return 结果
     */
    @Override
    public int deleteProjectAuctionById(Long id)
    {
        ProjectAuction projectAuction = projectAuctionMapper.selectProjectAuctionById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectAuction.getVrResource(),
                projectAuction.getImgResource(),
                projectAuction.getCoverResource(),
                projectAuction.getVrcover(),
                projectAuction.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("拍卖",projectAuction.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectAuctionId(id);
        return projectAuctionMapper.deleteProjectAuctionById(id);
    }

    @Override
    public Map<String, Object> selectProjectAuctionByNumber(String spaceId, boolean show) {
        ProjectAuction projectAuction = projectAuctionMapper.selectProjectAuctionByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectAuctionMapper.updatePageViews(spaceId);
            }
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (list != null && list.size() != 0) {
                projectAuction.setCollectState(1L);
            } else {
                projectAuction.setCollectState(0L);
            }
        }else {
            projectAuction.setCollectState(0L);
        }
        if (projectAuction.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectAuction.getProvinceId());
            projectAuction.setCityName(district.getName());
        }
        if (projectAuction.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectAuction.getCityId());
            projectAuction.setCityName(projectAuction.getCityName()+district.getName());
        }
        if (projectAuction.getAreaId()!=null){
            District district = districtMapper.selectDistrictById(projectAuction.getAreaId());
            projectAuction.setCityName(projectAuction.getCityName()+district.getName());
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectAuction.getServicePhone());
        if (sysUser!=null){
            projectAuction.setContactName(sysUser.getNickName());
            projectAuction.setContactPhone(sysUser.getPhonenumber());
            projectAuction.setQrCode(sysUser.getCodePic());
        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectAuction.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("space",projectAuction);
        if (projectAuction.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectAuction.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectAuctionBySerialNumber(String spaceId) {
        ProjectAuction projectAuction = projectAuctionMapper.selectProjectAuctionByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectAuction.getVrResource(),
                projectAuction.getImgResource(),
                projectAuction.getCoverResource(),
                projectAuction.getVrcover(),
                projectAuction.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("拍卖",projectAuction.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectAuctionId(projectAuction.getId());
        return projectAuctionMapper.deleteProjectAuctionById(projectAuction.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectAuction> projectAuctionList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectAuctionList) || projectAuctionList.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;
        for (ProjectAuction projectAuction : projectAuctionList) {
            if (projectAuctionList.indexOf(projectAuction)==0&&projectAuction.getAuctionName().equals("拍卖名称")){
                continue;
            }
            count++;
            try {
                if (projectAuction.getApprovalState()==null||STATE.contains(projectAuction.getApprovalState())){
                    projectAuction.setApprovalState(0L);
                }
                if (projectAuction.getSupplyUserId()==null){
                    projectAuction.setSupplyUserId(SecurityUtils.getUserId());
                }
                if (projectAuction.getAuctionName()==null||projectAuction.getAuctionName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少拍卖名称");
                    break;
                }
                projectAuction.setCreateBy(SecurityUtils.getUsername());
                projectAuction.setCreateTime(DateUtils.getNowDate());
                projectAuctionMapper.insertProjectAuction(projectAuction);
                successNum++;
                successMsg.append("<br/>" + successNum + "、拍卖 " + projectAuction.getAuctionName() + " 导入成功");
            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、拍卖 " + projectAuction.getAuctionName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectAuction modal = projectAuctionMapper.selectProjectAuctionById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("标地名称：" + modal.getAuctionName() + "<w:br/>");
        stringBuffer.append("拍卖类型：").append(modal.getAuctionType()).append("<w:br/>");
        stringBuffer.append("区域：" + modal.getAuctionArea() + "<w:br/>");
        stringBuffer.append("标的所在地：" + modal.getAuctionAddress() + "<w:br/>");
        stringBuffer.append("资产类型：" + modal.getAuctionAssets() + "<w:br/>");
        stringBuffer.append("拍卖状态：" + modal.getAuctionState() + "<w:br/>");
        stringBuffer.append("拍卖阶段：" + modal.getAuctionStage() + "<w:br/>");
        stringBuffer.append("上拍时间：" + modal.getAuctionTime() + "<w:br/>");
        stringBuffer.append("价格区间：" + modal.getAuctionPrice() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
